package com.san.system.controller;

import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.controller.BaseController;
import com.san.base.domain.CodeDO;
import com.san.base.domain.Tree;
import com.san.base.service.CodeService;
import com.san.common.annotation.Log;
import com.san.common.utils.Constant;
import com.san.common.utils.DateUtils;
import com.san.common.utils.MD5Utils;
import com.san.common.utils.R;
import com.san.common.utils.ShiroUtils;
import com.san.system.domain.MenuDO;
import com.san.system.domain.UserDO;
import com.san.system.service.MenuService;
import com.san.system.service.UserService;
import com.san.system.vo.UserVO;

@Controller
public class LoginController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	MenuService menuService;

	@Autowired
	UserService userService;
	
	@Autowired
	CodeService codeService;

	@GetMapping({ "/", "" })
	String welcome(Model model) {

		return "redirect:/login";
	}

	@Log("请求访问主页")
	@GetMapping({ "/index" })
	String index(Model model) {
		CodeDO codeDO = codeService.getByName(Constant.KEY_CHANGE_PASSWORD_DAYS);
		
		int days = 90;
		if (null != codeDO && null != codeDO.getCodeValue() && !"".equals(codeDO.getCodeValue())) {
			try {
				days = Integer.parseInt(codeDO.getCodeValue());
			} catch(Exception e) {
				logger.error("最大密码修改天数系统参数有误！", e);
			}
		}
		
		if (null == getUser().getPwdUpdateTime()
				|| DateUtils.differentDaysByMillisecond(getUser().getPwdUpdateTime(), new Date()) > days) {
			UserDO userDO = new UserDO();
			userDO.setUserId(getUser().getUserId());
			model.addAttribute("userDO", userDO);
			return "change_pwd";
		} else {
			List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
			model.addAttribute("menus", menus);
			model.addAttribute("name", getUser().getName());
			model.addAttribute("picUrl", "/images/logo.png");

			model.addAttribute("userName", getUser().getUserName());
			return "index";
		}
	}

	@GetMapping("/login")
	String login() {
		return "login";

	}

	@Log("登录")
	@PostMapping("/login")
	@ResponseBody
	R ajaxLogin(String username, String password) {
		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return R.ok();
		} catch (LockedAccountException e) {
			return R.error("账号已被锁定,请联系管理员");
		} catch (Exception e) {
			return R.error("用户名或密码错误");
		}
	}

	@GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/login";
	}

	@GetMapping("/main")
	String main() {
		return "main";
	}

	@PostMapping("/changePwd")
	@Log("修改密码")
	@ResponseBody
	R changePwd(UserVO userVO) {
		try {
			userService.resetPwd(userVO, getUser());
		} catch (Exception e) {
			return R.error(e.getMessage());
		}
		ShiroUtils.logout();
		return R.ok();
	}
}
